﻿using System.Diagnostics;
using System.IO;
using System.Runtime.CompilerServices;
using System.Text.RegularExpressions;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
using DynamicData;
using Shinva.LADModel.Abstractions;
using Shinva.LADModel.Helper;
using Shinva.LADModel.Models;
using Shinva.LADModel.Type.BitLogicOperations;
using Shinva.LADModel.Type.ComparatorOperations;
using Shinva.LADModel.Type.ConversionOperations;
using Shinva.LADModel.Type.Custom;
using Shinva.LADModel.Type.Mathfunctions;
using Shinva.LADModel.Type.MoveOperations;
using Shinva.LADModel.Type.TimerOperations;
using Shinva.LADModel.Type.WordLogicOperations;
using Shinva.Variables.Interface;
using Shinva.Variables.Models;
using Shinva.Variables.Type.bit;
using Shinva.Variables.Type.character;
using Shinva.Variables.Type.combination;
using Shinva.Variables.Type.floating;
using Shinva.Variables.Type.integer;
using Shinva.Variables.Type.time;

namespace Shinva.PLCModel.Helper
{
    /// <summary>
    /// 表示数组声明的解析结果
    /// </summary>
    public class ArrayInfo
    {
        public string ArrayName { get; set; } = string.Empty;  // 数组名称
        public int Length { get; set; }        // 数组长度
        public string ElementType { get; set; } = string.Empty; // 元素类型

        /// <summary>
        /// 解析数组声明并返回相关信息
        /// </summary>
        /// <param name="input">输入的数组声明字符串</param>
        /// <returns>包含数组名称、长度和元素类型的对象</returns>
        public static ArrayInfo ParseArrayDeclaration(string input)
        {
            // 定义正则表达式
            //string pattern = @"(\w+)$(\d+)\.\.(\d+)$\s+of\s+(.+)";
            string pattern = @"Array\[(\d+)\.\.(\d+)\]\s*of\s*(""[^""]+""|\w+)";
            Regex regex = new Regex(pattern);

            // 匹配输入字符串
            Match match = regex.Match(input);
            if (!match.Success)
            {
                throw new ArgumentException("Invalid array declaration format.");
            }

            // 提取匹配的分组
            string arrayName = "Array";         // 数组名称
            int lowerBound = int.Parse(match.Groups[1].Value); // 下界
            int upperBound = int.Parse(match.Groups[2].Value); // 上界
            string elementType = match.Groups[3].Value.Trim('"'); // 元素类型（去除双引号）

            // 计算数组长度
            int length = upperBound - lowerBound + 1;

            // 返回结果
            return new ArrayInfo
            {
                ArrayName = arrayName,
                Length = length,
                ElementType = elementType
            };
        }
        /// <summary>
        /// 从字符串中提取方括号中的数字
        /// </summary>
        /// <param name="input">输入的字符串</param>
        /// <returns>方括号中的数字</returns>
        public static int ExtractNumberFromBracket(string input)
        {
            // 定义正则表达式
            string pattern = @"String\[(\d+)\]";
            Regex regex = new Regex(pattern);

            // 匹配输入字符串
            Match match = regex.Match(input);
            if (match.Success)
            {
                // 提取匹配的数字并转换为整数
                return int.Parse(match.Groups[1].Value);
            }
            else
            {
                throw new ArgumentException("Invalid input format. Expected a string in the format 'string[<number>]'.");
            }
        }
    }
    /// <summary>
    /// 从西门子XML文件中解析的文件信息
    /// </summary>
    public class FileInfo
    {
        //文件名
        public string FileName { get; set; } = string.Empty;
        //文件路径
        public string FilePath { get; set; } = string.Empty;
        public string FileType { get; set; } = string.Empty;
        public Sections_T Sections_T { get; set; } = new Sections_T();
        public List<StructuredText_T> STList { get; set; } = new List<StructuredText_T>();
        public List<FlgNet_T> LadList { get; set; } = new List<FlgNet_T>();
        public string ProgrammingLanguage { get; set; } = string.Empty;
        public string InstanceOfName { get; set; } = string.Empty;
        //变量表
        public PlcStruct PlcStruct { get; set; } = new PlcStruct();

        //图结构
        public Diagram diagram { get; set; } = new Diagram();

    }
    public class ParseXmzXml
    {
        public string folderPath { get; set; } = string.Empty;
        public List<string> XmlFiles { get; set; } = new List<string>();
        //静态变量
        static readonly XNamespace ns_Interface = "http://www.siemens.com/automation/Openness/SW/Interface/v5";
        static readonly XNamespace ns_ST = "http://www.siemens.com/automation/Openness/SW/NetworkSource/StructuredText/v3";
        static readonly XNamespace ns_lad = "http://www.siemens.com/automation/Openness/SW/NetworkSource/FlgNet/v4";
        public List<FileInfo> fileInfos = new List<FileInfo>();

        /// <summary>
        /// 获取指定文件夹下的所有 .xml 文件的全路径列表
        /// </summary>
        /// <returns>包含所有 .xml 文件全路径的列表</returns>
        private static List<string> GetXmlFiles(string folderPath)
        {
            // 检查文件夹是否存在
            if (!Directory.Exists(folderPath))
            {
                throw new DirectoryNotFoundException($"文件夹路径不存在：{folderPath}");
            }

            // 获取文件夹下所有 .json 文件的全路径
            string[] xmlFiles = Directory.GetFiles(folderPath, "*.xml", SearchOption.AllDirectories);

            // 将结果转换为 List<string> 并返回
            return new List<string>(xmlFiles);
        }

        /// <summary>
        /// 解析西门子导出工程文件夹下所有文件
        /// </summary>
        /// <param name="folderPath"></param>
        /// <returns></returns>
        public static List<FileInfo> ParseXmlFiles(string folderPath)
        {
            var xmlFiles = GetXmlFiles(folderPath);
            List<FileInfo> fileInfos = new List<FileInfo>();
            foreach (var file in xmlFiles)
            {
                FileInfo fileInfo = new();
                #region 提取xml
                try
                {
                    // 加载 XML 文件
                    XDocument document = XDocument.Load(file);
                    //解析文件名

                    XElement? Attr = null;
                    var instanceDB = document.Descendants("SW.Blocks.InstanceDB").FirstOrDefault();
                    var globalDB = document.Descendants("SW.Blocks.GlobalDB").FirstOrDefault();
                    var fB = document.Descendants("SW.Blocks.FB").FirstOrDefault();
                    var fC = document.Descendants("SW.Blocks.FC").FirstOrDefault();
                    var oB = document.Descendants("SW.Blocks.OB").FirstOrDefault();
                    var plcS = document.Descendants("SW.Types.PlcStruct").FirstOrDefault();

                    if (instanceDB != null)
                    {
                        Attr = instanceDB.Element("AttributeList");
                        fileInfo.FileType = "InstanceDB";
                    }
                    if (globalDB != null)
                    {
                        Attr = globalDB.Element("AttributeList");
                        fileInfo.FileType = "GlobalDB";
                    }
                    if (fB != null)
                    {
                        Attr = fB.Element("AttributeList");
                        fileInfo.FileType = "FB";
                    }
                    if (fC != null)
                    {
                        Attr = fC.Element("AttributeList");
                        fileInfo.FileType = "FC";
                    }
                    if (oB != null)
                    {
                        Attr = oB.Element("AttributeList");
                        fileInfo.FileType = "OB";
                    }
                    if (plcS != null)
                    {
                        Attr = plcS.Element("AttributeList");
                        fileInfo.FileType = "PlcStruct";
                    }
                    fileInfo.FileName = Path.GetFileNameWithoutExtension(file);
                    fileInfo.FilePath = file;
                    fileInfo.ProgrammingLanguage = Attr?.Element("ProgrammingLanguage")?.Value ?? string.Empty;
                    fileInfo.InstanceOfName = Attr?.Element("InstanceOfName")?.Value ?? string.Empty;



                    // 使用 LINQ 查询定位 Sections 节点只有一个
                    var sectionsElement = document.Descendants(ns_Interface + "Sections").FirstOrDefault();

                    if (sectionsElement != null)
                    {
                        // 移除命名空间
                        XElement cleanedElement = RemoveNamespace(sectionsElement);

                        // 反序列化
                        Sections_T sections = DeserializeFromXElement<Sections_T>(cleanedElement);

                        // 调试输出具体内容
                        Debug.WriteLine($"Sections 节点解析成功，包含 {sections.Section.Length} 个 Section");
                        //foreach (var section in sections.Section)
                        //{
                        //    Debug.WriteLine($"Section Name: {section.Name}, Members Count: {section.Member.Length}");
                        //}
                        fileInfo.Sections_T = sections;
                    }
                    else
                    {
                        Debug.WriteLine("没有找到任何 Sections 节点");
                    }

                    //定位st
                    var stElements = document.Descendants(ns_ST + "StructuredText").ToList();
                    if (stElements.Any())
                    {
                        var structuredTexts = new List<StructuredText_T>();

                        foreach (var stElement in stElements)
                        {
                            // 移除命名空间
                            XElement cleanedElement = RemoveNamespace(stElement);

                            // 反序列化
                            StructuredText_T structuredText = DeserializeFromXElement<StructuredText_T>(cleanedElement);
                            structuredTexts.Add(structuredText);
                        }
                        fileInfo.STList = structuredTexts;
                    }
                    else
                    {
                        Debug.WriteLine("没有找到任何 StructuredText 节点");
                    }
                    //定位lad
                    var ladElements = document.Descendants(ns_lad + "FlgNet").ToList();
                    if (ladElements.Any())
                    {
                        var flgNets = new List<FlgNet_T>();
                        foreach (var ladElement in ladElements)
                        {
                            // 移除命名空间
                            XElement cleanedElement = RemoveNamespace(ladElement);

                            // 反序列化
                            FlgNet_T flgNet = DeserializeFromXElement<FlgNet_T>(cleanedElement);
                            flgNets.Add(flgNet);
                        }

                        fileInfo.LadList = flgNets;
                    }
                    else
                    {
                        Debug.WriteLine("没有找到任何 FlgNet 节点");
                    }
                    Debug.WriteLine($"文件 {file} 逻辑提取成功");

                }
                catch (XmlException ex)
                {
                    Debug.WriteLine($"XML 解析错误: {ex.Message}");
                }
                catch (IOException ex)
                {
                    Debug.WriteLine($"文件读取错误: {ex.Message}");
                }
                catch (Exception ex)
                {
                    Debug.WriteLine($"反序列化或其他错误: {ex.Message}");
                }
                #endregion

                #region 放入数据结构
                fileInfo.PlcStruct.Name = fileInfo.FileName;
                ParseSection(fileInfo.Sections_T, fileInfo.PlcStruct);
                ParseFlgNetList(fileInfo.LadList, fileInfo.diagram);
                #endregion
                fileInfos.Add(fileInfo);
            }

            return fileInfos;
        }
        /// <summary>
        /// 递归移除元素及其子元素的命名空间
        /// </summary>
        /// <param name="element">需要处理的 XElement</param>
        /// <returns>移除命名空间后的新 XElement</returns>
        private static XElement RemoveNamespace(XElement element)
        {
            return new XElement(
            element.Name.LocalName,
            element.Attributes().Where(a => !a.IsNamespaceDeclaration),
            element.Elements().Select(RemoveNamespace),
            element.HasElements ? null : element.Value);
        }
        /// <summary>
        /// 从 XElement 反序列化为指定类型的对象
        /// </summary>
        /// <typeparam name="T">目标类型</typeparam>
        /// <param name="element">XElement 实例</param>
        /// <returns>反序列化后的对象</returns>
        private static T DeserializeFromXElement<T>(XElement element)
        {
            if (element == null)
                throw new ArgumentNullException(nameof(element));

            XmlSerializer serializer = new XmlSerializer(typeof(T));
            using (StringReader reader = new StringReader(element.ToString()))
            {
                return (T)serializer.Deserialize(reader);
            }
        }


        #region 转换西门子数据结构到自定义数据结构的辅助方法
        /// <summary>
        /// 解析Sections，每个section是一个结构体
        /// </summary>
        /// <param name="sections_T"></param>
        /// <param name="plcStruct"></param>
        private static void ParseSection(Sections_T sections_T, PlcStruct plcStruct)
        {
            if (sections_T.Section.Length > 0)
            {
                foreach (var sectionItem in sections_T.Section)
                {
                    string sectionName = Enum.GetName(typeof(SectionName_TE), sectionItem.Name) ?? string.Empty;
                    PlcStruct sectionStruct = new PlcStruct(sectionName);
                    if (sectionItem.Member != null && sectionItem.Member.Length > 0)
                    {

                        if (sectionName != null && sectionName != string.Empty && sectionItem.Member.Length > 0)
                        {
                            foreach (var memberItem in sectionItem.Member)
                            {
                                ParseMenber(memberItem, sectionStruct);
                            }
                        }
                        plcStruct.AddMember(sectionStruct);
                    }
                    else
                    {
                        plcStruct.AddMember(sectionStruct);
                    }

                }
            }
        }
        /// <summary>
        /// 解析Member,如果是标准struct,则进行递归解析
        /// </summary>
        /// <param name="member_T"></param>
        /// <param name="sectionStruct"></param>
        private static void ParseMenber(Member_T member_T, PlcStruct sectionStruct)
        {
            string dataType = member_T.Datatype;
            string name = member_T.Name;
            switch (dataType)
            {
                //处理基本数据类型
                //位数据类型
                case "Bool":
                    sectionStruct.AddMember(new PlcBool() { Name = name });
                    break;
                case "Byte":
                    sectionStruct.AddMember(new PlcByte() { Name = name });
                    break;
                case "Word":
                    sectionStruct.AddMember(new PlcWord() { Name = name });
                    break;
                case "DWord":
                    sectionStruct.AddMember(new PlcDWord() { Name = name });
                    break;
                //整数数据类型
                case "USInt":
                    sectionStruct.AddMember(new PlcUSInt() { Name = name });
                    break;
                case "SInt":
                    sectionStruct.AddMember(new PlcSInt() { Name = name });
                    break;
                case "UInt":
                    sectionStruct.AddMember(new PlcUInt() { Name = name });
                    break;
                case "Int":
                    sectionStruct.AddMember(new PlcInt() { Name = name });
                    break;
                case "UDInt":
                    sectionStruct.AddMember(new PlcUDInt() { Name = name });
                    break;
                case "DInt":
                    sectionStruct.AddMember(new PlcDInt() { Name = name });
                    break;
                //浮点数据类型
                case "Real":
                    sectionStruct.AddMember(new PlcReal() { Name = name });
                    break;
                case "LReal":
                    sectionStruct.AddMember(new PlcLReal() { Name = name });
                    break;
                //时间数据类型
                case "Time":
                    sectionStruct.AddMember(new PlcTime(0) { Name = name });
                    break;
                case "Date":
                    sectionStruct.AddMember(new PlcDate() { Name = name });
                    break;
                case "TOD":
                    sectionStruct.AddMember(new PlcToD(new TimeSpan()) { Name = name });
                    break;
                case "DTL":
                    sectionStruct.AddMember(new PlcDTL() { Name = name });
                    break;
                //字符串数据类型
                case "Char":
                    sectionStruct.AddMember(new PlcChar() { Name = name });
                    break;
                case "WChar":
                    sectionStruct.AddMember(new PlcWChar() { Name = name });
                    break;
                case "String":
                    sectionStruct.AddMember(new PlcArray(name, new PlcWChar() { Name = name }, 256));
                    break;
                case "WString":
                    //sectionStruct.AddMember(new PlcChar(name, '0'));
                    break;
                case "IEC_TIMER":
                    break;
                case "Void":
                    //先用bool占位
                    sectionStruct.AddMember(new PlcBool() { Name = $"{name}_void" });
                    break;
                case "Struct":
                    // 处理结构体类型
                    var subStrcut = new PlcStruct(name);
                    if (member_T.Items != null)
                    {
                        foreach (var item in member_T.Items)
                        {
                            if (item != null && item is Member_T)
                            {
                                ParseMenber(item as Member_T, subStrcut);
                            }
                        }
                    }
                    sectionStruct.AddMember(subStrcut);
                    break;
                default:
                    //处理Array开始的数组
                    if (dataType.StartsWith("Array["))
                    {
                        // 处理数组类型
                        // 解析数组声明

                        ArrayInfo arrayInfo = ArrayInfo.ParseArrayDeclaration(dataType);
                        //根据不同的类型创建不同的数组
                        switch (arrayInfo.ElementType)
                        {
                            //处理基本数据类型
                            //位数据类型
                            //位数据类型
                            case "Bool":
                                sectionStruct.AddMember(new PlcBool() { Name = name });
                                break;
                            case "Byte":
                                sectionStruct.AddMember(new PlcByte() { Name = name });
                                break;
                            case "Word":
                                sectionStruct.AddMember(new PlcWord() { Name = name });
                                break;
                            case "DWord":
                                sectionStruct.AddMember(new PlcDWord() { Name = name });
                                break;
                            //整数数据类型
                            case "USInt":
                                sectionStruct.AddMember(new PlcUSInt() { Name = name });
                                break;
                            case "SInt":
                                sectionStruct.AddMember(new PlcSInt() { Name = name });
                                break;
                            case "UInt":
                                sectionStruct.AddMember(new PlcUInt() { Name = name });
                                break;
                            case "Int":
                                sectionStruct.AddMember(new PlcInt() { Name = name });
                                break;
                            case "UDInt":
                                sectionStruct.AddMember(new PlcUDInt() { Name = name });
                                break;
                            case "DInt":
                                sectionStruct.AddMember(new PlcDInt() { Name = name });
                                break;
                            //浮点数据类型
                            case "Real":
                                sectionStruct.AddMember(new PlcReal() { Name = name });
                                break;
                            case "LReal":
                                sectionStruct.AddMember(new PlcLReal() { Name = name });
                                break;
                            //时间数据类型
                            case "Time":
                                sectionStruct.AddMember(new PlcTime(0) { Name = name });
                                break;
                            case "Date":
                                sectionStruct.AddMember(new PlcDate() { Name = name });
                                break;
                            case "TOD":
                                sectionStruct.AddMember(new PlcToD(new TimeSpan()) { Name = name });
                                break;
                            case "DTL":
                                sectionStruct.AddMember(new PlcDTL() { Name = name });
                                break;
                            //字符串数据类型
                            case "Char":
                                sectionStruct.AddMember(new PlcChar() { Name = name });
                                break;
                            case "WChar":
                                sectionStruct.AddMember(new PlcWChar() { Name = name });
                                break;
                            case "String":
                                sectionStruct.AddMember(new PlcArray(name, new PlcWChar() { Name = name }, 256));
                                break;
                            case "WString":
                                //sectionStruct.AddMember(new PlcChar(name, '0'));
                                break;
                            case "IEC_TIMER":
                                break;
                            default:
                                sectionStruct.AddMember(new PlcArray(name, new PlcStruct(arrayInfo.ElementType, name), arrayInfo.Length));
                                break;
                        }


                    }
                    else if (dataType.StartsWith("String["))
                    {
                        int length = ArrayInfo.ExtractNumberFromBracket(dataType);
                        sectionStruct.AddMember(new PlcArray(name, new PlcChar() { Name = name }, length));
                    }
                    else
                    {
                        sectionStruct.AddMember(new PlcStruct(name));
                        Debug.WriteLine($"不支持的数据类型: {dataType}，请检查数据类型定义。");
                    }
                    break;
            }
        }


        private static void ParseFlgNetList(List<FlgNet_T> flgNet_list, Diagram nodeTree)
        {
            if (flgNet_list.Count > 0)
            {
                foreach (var flgNetItem in flgNet_list)
                {
                    //解析每个网络
                    //数据节点字典
                    Dictionary<string, DataPointer> accessDic = new Dictionary<string, DataPointer>();
                    //元件节点字典
                    Dictionary<string, IGraphNode> partDic = new Dictionary<string, IGraphNode>();
                    //网络
                    var newNet = new Powerrail();
                    nodeTree.Networks.Add(newNet);
                    if (flgNetItem.Parts != null && flgNetItem.Parts.Length > 0)
                    {
                        ParseParts(flgNetItem.Parts, accessDic, partDic);
                    }
                    //Debug.WriteLine(flgNetItem.ToString());
                    if (flgNetItem.Wires != null && flgNetItem.Wires.Wire.Length > 0)
                    {
                        //IdentCon 数据节点
                        //NameCon 指令对应的变量名
                        //OpenCon 根据博图查看为空节点用于连接NameCon
                        //Openbranch 推测为O,竖着的虚拟节点
                        //Powerrail 母线，能流的开始
                        foreach (var wire in flgNetItem.Wires.Wire)
                        {
                            //Debug.WriteLine($"wire:{wire}");
                            ParseWire(wire, accessDic, partDic, newNet);
                        }
                    }
                }
            }
        }
        /// <summary>
        /// 解析所有节点
        /// </summary>
        /// <param name="parts"></param>
        private static void ParseParts(Object[] parts,
            Dictionary<string, DataPointer> accessDic,
            Dictionary<string, IGraphNode> partDict
            )
        {
            foreach (var part in parts)
            {
                if (part is Part_T)
                {
                    var _part = (Part_T)part;
                    ParsePart(_part, partDict);
                }
                else if (part is Call_T)
                {
                    var _call = (Call_T)part;
                    ParseCall(_call, partDict);
                }
                else if (part is Access_T)
                {
                    var _access = (Access_T)part;
                    string access_str = ParseAccess(_access);
                    if (access_str.Contains('+'))
                    {
                        //格式：uid+scope+value
                        var str_array = access_str.Split('+');
                        if (str_array.Length != 3)
                        {
                            Log.LogMessage("严重错误,应该包含++!!!!!!!!!!!!");
                            Environment.Exit(0); // 使用退出代码 0 退出程序
                        }
                        var accessValue = access_str.Split('+')[2];
                        var uid = access_str.Split('+')[0];
                        var scope = access_str.Split('+')[1];


                        if (accessDic.ContainsKey(uid))
                        {
                            Debug.WriteLine($"数据节点uid重复：{uid}");
                        }
                        else
                        {
                            var dataPointer = new DataPointer();
                            dataPointer.Symbols.Add(scope);
                            dataPointer.Symbols.Add(accessValue);
                            //switch (scope)
                            //{
                            //    case "LiteralConstant":

                            //        dataPointer.Symbols.Add(accessValue);
                            //        break;
                            //    case "GlobalVariable":
                            //        dataPointer.Symbols.Add(accessValue);
                            //        break;
                            //    case "LocalVariable":
                            //        dataPointer.Symbols.Add(accessValue);
                            //        break;
                            //    default:
                            //        break;
                            //}
                            accessDic.Add(uid, dataPointer);
                        }
                    }
                    else
                    {
                        Log.LogMessage($"严重错误,应该包含++!!!!!!!!!!!!{access_str}");
                    }

                }
            }
        }
        private static void ParsePart(Part_T part_T, Dictionary<string, IGraphNode> partDict)
        {
            if (part_T != null)
            {
                var uid = part_T.UId;
                var uid_str = part_T.UId.ToString();
                var name = part_T.Name;
                Debug.WriteLine($"{uid},{name}");
                if (part_T.Negated != null && part_T.Negated.Length > 0)
                {
                    foreach (var negatedItem in part_T.Negated)
                    {
                        Debug.WriteLine($"取反{negatedItem.Name}");
                    }
                }
                //Debug.WriteLine($"统计-----:{part_T.Name}");
                switch (part_T.Name)
                {
                    //虚拟节点
                    case "O":
                        var o = new VirtualNode() { Name = $"O_{uid}" };
                        partDict.Add(uid_str, o);
                        break;
                    //位指令
                    case "Contact":
                        var contact = new Contact() { Name = $"Contact_{uid}" };
                        partDict.Add(uid_str, contact);
                        break;
                    case "Not":
                        partDict.Add(uid_str, new NOT() { Name = $"NOT_{uid}" });
                        break;
                    case "Coil":
                        var coil = new Coil() { Name = $"Coil_{uid}" };
                        partDict.Add(uid_str, coil);
                        break;
                    case "RCoil":
                        var rcoil = new RCoil() { Name = $"RCoil_{uid}" };
                        partDict.Add(uid_str, rcoil);
                        break;
                    case "SCoil":
                        var scoil = new SCoil() { Name = $"RCoil_{uid}" };
                        partDict.Add(uid_str, scoil);
                        break;
                    case "PContact":
                        partDict.Add(uid_str, new PContact() { Name = $"PContact_{uid}" });
                        break;
                    case "NContact":
                        partDict.Add(uid_str, new NContact() { Name = $"NContact_{uid}" });
                        break;
                    case "PCoil":
                        break;
                    case "NCoil":

                        break;
                    //定时器
                    case "TON":
                        //是一个FB,对于其中的fb还需要进一步处理
                        //TODO!!
                        {
                            partDict.Add(uid_str, new TON() { Name = $"TON_{uid}" });
                        }
                        break;
                    case "TOF":
                        break;
                    case "TONR":
                        break;
                    case "CoilTON":
                        {
                            partDict.Add(uid_str, new CoilTON() { Name = $"CoilTON_{uid}" });
                        }
                        break;
                    case "CoilTOF":
                        break;
                    case "CoilTONR":
                        {
                            partDict.Add(uid_str, new CoilTONR() { Name = $"CoilTONR_{uid}" });
                        }
                        break;
                    //计数器

                    case "CTU":
                        break;
                    case "CTD":
                        break;
                    case "CTUD":
                        break;

                    //比较操作
                    //两个数
                    case "Eq":
                    case "Ne":
                    case "Ge":
                    case "Le":
                    case "Gt":
                    case "Lt":
                    //三个数
                    case "InRange":
                    case "OutRange":
                        {
                            //var eq = new Eq() { Name = $"Eq_{uid}", SrcType = "Int" };
                            //partDict.Add(uid.ToString(), eq);
                            string compareValueType = string.Empty;
                            //用于指定比较类型
                            if (part_T.TemplateValue != null && part_T.TemplateValue.Length > 0)
                            {
                                foreach (var templateItem in part_T.TemplateValue)
                                {
                                    if (templateItem is TemplateValue_T templateValue_)
                                    {
                                        if (templateValue_.Type == TemplateType_TE.Type
                                            && templateValue_.Name == "SrcType")
                                        {
                                            compareValueType = templateValue_.Value;
                                        }
                                    }
                                }
                            }
                            //根据类型定义比较变量
                            //var compareNode=new ComparatorTwo<>
                            if (compareValueType != string.Empty)
                            {
                                //两个数
                                if (Enum.TryParse<DataType>(compareValueType, out DataType dataType) &&
                                    Enum.TryParse<ComparisonType>(part_T.Name, out ComparisonType comparisonType))
                                {
                                    switch (dataType)
                                    {
                                        case DataType.Bool:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcBool>(comparisonType));
                                            break;
                                        case DataType.Byte:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcByte>(comparisonType));
                                            break;
                                        case DataType.Word:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcWord>(comparisonType));
                                            break;
                                        case DataType.DWord:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcDWord>(comparisonType));
                                            break;
                                        case DataType.USInt:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcUSInt>(comparisonType));
                                            break;
                                        case DataType.SInt:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcSInt>(comparisonType));
                                            break;
                                        case DataType.UInt:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcUInt>(comparisonType));
                                            break;
                                        case DataType.Int:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcInt>(comparisonType));
                                            break;
                                        case DataType.UDInt:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcUDInt>(comparisonType));
                                            break;
                                        case DataType.DInt:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcDInt>(comparisonType));
                                            break;
                                        case DataType.Real:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcReal>(comparisonType));
                                            break;
                                        case DataType.LReal:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcLReal>(comparisonType));
                                            break;
                                        case DataType.Time:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcTime>(comparisonType));
                                            break;
                                        case DataType.Char:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcChar>(comparisonType));
                                            break;
                                        case DataType.WChar:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcWChar>(comparisonType));
                                            break;
                                        case DataType.String:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcWChar>(comparisonType));
                                            break;
                                        case DataType.WString:
                                            partDict.Add(uid_str, new ComparatorTwo<PlcWChar>(comparisonType));
                                            break;
                                        default:
                                            Debug.WriteLine($"不支持的比较类型: {compareValueType}");
                                            Log.LogMessage($"指令comparetwo{part_T.Name}不支持的比较类型: {compareValueType}，请检查数据类型定义。");
                                            break;
                                    }
                                }
                                else if (Enum.TryParse<DataType>(compareValueType, out DataType dataType3) &&
                                    Enum.TryParse<RangeType>(part_T.Name, out RangeType rangeType))
                                {
                                    switch (dataType3)
                                    {
                                        case DataType.USInt:
                                            partDict.Add(uid_str, new Range<PlcUSInt>(rangeType));
                                            break;
                                        case DataType.SInt:
                                            partDict.Add(uid_str, new Range<PlcSInt>(rangeType));
                                            break;
                                        case DataType.UInt:
                                            partDict.Add(uid_str, new Range<PlcUInt>(rangeType));
                                            break;
                                        case DataType.Int:
                                            partDict.Add(uid_str, new Range<PlcInt>(rangeType));
                                            break;
                                        case DataType.UDInt:
                                            partDict.Add(uid_str, new Range<PlcUDInt>(rangeType));
                                            break;
                                        case DataType.DInt:
                                            partDict.Add(uid_str, new Range<PlcDInt>(rangeType));
                                            break;
                                        case DataType.Real:
                                            partDict.Add(uid_str, new Range<PlcReal>(rangeType));
                                            break;
                                        case DataType.LReal:
                                            partDict.Add(uid_str, new Range<PlcLReal>(rangeType));
                                            break;
                                        default:
                                            Log.LogMessage($"指令range:{part_T.Name}不支持的比较类型: {compareValueType}，请检查数据类型定义。");
                                            break;
                                    }
                                }
                                else
                                {
                                    Debug.WriteLine($"不支持的比较的数据类型类型: {compareValueType}");
                                }

                            }
                        }
                        break;
                    //数学函数
                    case "Add":
                        {
                            //输入的数量
                            string inCount = string.Empty;
                            //计算的变量类型
                            string addValueType = string.Empty;
                            //自动类型判断
                            bool autoType = false;
                            if (part_T.TemplateValue != null && part_T.TemplateValue.Length > 0)
                            {
                                foreach (var templateItem in part_T.TemplateValue)
                                {
                                    if (templateItem is TemplateValue_T templateValue_)
                                    {
                                        if (templateValue_.Type == TemplateType_TE.Type
                                            && templateValue_.Name == "SrcType")
                                        {
                                            addValueType = templateValue_.Value;
                                        }
                                        if (templateValue_.Type == TemplateType_TE.Cardinality
                                            && templateValue_.Name == "Card")
                                        {
                                            inCount = templateValue_.Value;
                                        }
                                    }
                                }
                            }
                            if (part_T.AutomaticTyped != null && part_T.AutomaticTyped.Length > 0)
                            {
                                foreach (var automatic in part_T.AutomaticTyped)
                                {
                                    if (automatic is AutomaticTyped_T automaticValue_)
                                    {
                                        if (automaticValue_.Name == "SrcType")
                                        {
                                            autoType = true;
                                        }
                                    }
                                }
                            }
                            if (inCount != string.Empty && autoType)
                            {
                                //先放一个基类吧，先不考虑
                                partDict.Add(uid_str, new Add<PlcMemberBase>(int.Parse(inCount)));
                            }
                            else if (inCount != string.Empty && addValueType != string.Empty)
                            {
                                if (Enum.TryParse<DataType>(addValueType, out DataType dataType))
                                {
                                    switch (dataType)
                                    {
                                        case DataType.USInt:
                                            partDict.Add(uid_str, new Add<PlcUSInt>(int.Parse(inCount)));
                                            break;
                                        case DataType.SInt:
                                            partDict.Add(uid_str, new Add<PlcSInt>(int.Parse(inCount)));
                                            break;
                                        case DataType.UInt:
                                            partDict.Add(uid_str, new Add<PlcUInt>(int.Parse(inCount)));
                                            break;
                                        case DataType.Int:
                                            partDict.Add(uid_str, new Add<PlcInt>(int.Parse(inCount)));
                                            break;
                                        case DataType.UDInt:
                                            partDict.Add(uid_str, new Add<PlcUDInt>(int.Parse(inCount)));
                                            break;
                                        case DataType.DInt:
                                            partDict.Add(uid_str, new Add<PlcDInt>(int.Parse(inCount)));
                                            break;
                                        case DataType.Real:
                                            partDict.Add(uid_str, new Add<PlcReal>(int.Parse(inCount)));
                                            break;
                                        case DataType.LReal:
                                            partDict.Add(uid_str, new Add<PlcLReal>(int.Parse(inCount)));
                                            break;
                                        default:
                                            Debug.WriteLine($"不支持的比较类型: {addValueType}");
                                            Log.LogMessage($"指令comparetwo{part_T.Name}不支持的比较类型: {addValueType}，请检查数据类型定义。");
                                            break;
                                    }
                                }
                                else
                                {
                                    Debug.WriteLine($"不支持的比较的数据类型类型: {addValueType}");
                                    Log.LogMessage($"指令comparetwo{part_T.Name}不支持的比较类型: {addValueType}，请检查数据类型定义。");
                                }
                            }

                        }
                        break;
                    case "Sub":
                        {
                            //计算的变量类型
                            string subValueType = string.Empty;
                            //自动类型判断
                            bool autoType = false;
                            if (part_T.TemplateValue != null && part_T.TemplateValue.Length > 0)
                            {
                                foreach (var templateItem in part_T.TemplateValue)
                                {
                                    if (templateItem is TemplateValue_T templateValue_)
                                    {
                                        if (templateValue_.Type == TemplateType_TE.Type
                                            && templateValue_.Name == "SrcType")
                                        {
                                            subValueType = templateValue_.Value;
                                        }
                                    }
                                }
                            }
                            if (part_T.AutomaticTyped != null && part_T.AutomaticTyped.Length > 0)
                            {
                                foreach (var automatic in part_T.AutomaticTyped)
                                {
                                    if (automatic is AutomaticTyped_T automaticValue_)
                                    {
                                        if (automaticValue_.Name == "SrcType")
                                        {
                                            autoType = true;
                                        }
                                    }
                                }
                            }
                            if (autoType)
                            {
                                //先放一个基类吧，先不考虑
                                partDict.Add(uid_str, new Sub<PlcMemberBase>());
                            }
                            else if (subValueType != string.Empty)
                            {
                                if (Enum.TryParse<DataType>(subValueType, out DataType dataType))
                                {
                                    switch (dataType)
                                    {
                                        case DataType.USInt:
                                            partDict.Add(uid_str, new Sub<PlcUSInt>());
                                            break;
                                        case DataType.SInt:
                                            partDict.Add(uid_str, new Sub<PlcSInt>());
                                            break;
                                        case DataType.UInt:
                                            partDict.Add(uid_str, new Sub<PlcUInt>());
                                            break;
                                        case DataType.Int:
                                            partDict.Add(uid_str, new Sub<PlcInt>());
                                            break;
                                        case DataType.UDInt:
                                            partDict.Add(uid_str, new Sub<PlcUDInt>());
                                            break;
                                        case DataType.DInt:
                                            partDict.Add(uid_str, new Sub<PlcDInt>());
                                            break;
                                        case DataType.Real:
                                            partDict.Add(uid_str, new Sub<PlcReal>());
                                            break;
                                        case DataType.LReal:
                                            partDict.Add(uid_str, new Sub<PlcLReal>());
                                            break;
                                        default:
                                            Debug.WriteLine($"不支持的比较类型: {subValueType}");
                                            Log.LogMessage($"指令comparetwo{part_T.Name}不支持的比较类型: {subValueType}，请检查数据类型定义。");
                                            break;
                                    }
                                }
                                else
                                {
                                    Debug.WriteLine($"不支持的比较的数据类型类型: {subValueType}");
                                    Log.LogMessage($"指令comparetwo{part_T.Name}不支持的比较类型: {subValueType}，请检查数据类型定义。");
                                }
                            }
                        }
                        break;
                    case "Mul":
                        {
                            //输入的数量
                            string inCount = string.Empty;
                            //计算的变量类型
                            string mulValueType = string.Empty;
                            //自动类型判断
                            bool autoType = false;
                            if (part_T.TemplateValue != null && part_T.TemplateValue.Length > 0)
                            {
                                foreach (var templateItem in part_T.TemplateValue)
                                {
                                    if (templateItem is TemplateValue_T templateValue_)
                                    {
                                        if (templateValue_.Type == TemplateType_TE.Type
                                            && templateValue_.Name == "SrcType")
                                        {
                                            mulValueType = templateValue_.Value;
                                        }
                                        if (templateValue_.Type == TemplateType_TE.Cardinality
                                            && templateValue_.Name == "Card")
                                        {
                                            inCount = templateValue_.Value;
                                        }
                                    }
                                }
                            }
                            if (part_T.AutomaticTyped != null && part_T.AutomaticTyped.Length > 0)
                            {
                                foreach (var automatic in part_T.AutomaticTyped)
                                {
                                    if (automatic is AutomaticTyped_T automaticValue_)
                                    {
                                        if (automaticValue_.Name == "SrcType")
                                        {
                                            autoType = true;
                                        }
                                    }
                                }
                            }
                            if (inCount != string.Empty && autoType)
                            {
                                //先放一个基类吧，先不考虑
                                partDict.Add(uid_str, new Mul<PlcMemberBase>(int.Parse(inCount)));
                            }
                            else if (inCount != string.Empty && mulValueType != string.Empty)
                            {
                                if (Enum.TryParse<DataType>(mulValueType, out DataType dataType))
                                {
                                    switch (dataType)
                                    {
                                        case DataType.USInt:
                                            partDict.Add(uid_str, new Mul<PlcUSInt>(int.Parse(inCount)));
                                            break;
                                        case DataType.SInt:
                                            partDict.Add(uid_str, new Mul<PlcSInt>(int.Parse(inCount)));
                                            break;
                                        case DataType.UInt:
                                            partDict.Add(uid_str, new Mul<PlcUInt>(int.Parse(inCount)));
                                            break;
                                        case DataType.Int:
                                            partDict.Add(uid_str, new Mul<PlcInt>(int.Parse(inCount)));
                                            break;
                                        case DataType.UDInt:
                                            partDict.Add(uid_str, new Mul<PlcUDInt>(int.Parse(inCount)));
                                            break;
                                        case DataType.DInt:
                                            partDict.Add(uid_str, new Mul<PlcDInt>(int.Parse(inCount)));
                                            break;
                                        case DataType.Real:
                                            partDict.Add(uid_str, new Mul<PlcReal>(int.Parse(inCount)));
                                            break;
                                        case DataType.LReal:
                                            partDict.Add(uid_str, new Mul<PlcLReal>(int.Parse(inCount)));
                                            break;
                                        default:
                                            Debug.WriteLine($"不支持的比较类型: {mulValueType}");
                                            Log.LogMessage($"指令comparetwo{part_T.Name}不支持的比较类型: {mulValueType}，请检查数据类型定义。");
                                            break;
                                    }
                                }
                                else
                                {
                                    Debug.WriteLine($"不支持的比较的数据类型类型: {mulValueType}");
                                    Log.LogMessage($"指令comparetwo{part_T.Name}不支持的比较类型: {mulValueType}，请检查数据类型定义。");
                                }
                            }
                        }
                        break;
                    case "Div":
                        {
                            //计算的变量类型
                            string divValueType = string.Empty;
                            //自动类型判断
                            bool autoType = false;
                            if (part_T.TemplateValue != null && part_T.TemplateValue.Length > 0)
                            {
                                foreach (var templateItem in part_T.TemplateValue)
                                {
                                    if (templateItem is TemplateValue_T templateValue_)
                                    {
                                        if (templateValue_.Type == TemplateType_TE.Type
                                            && templateValue_.Name == "SrcType")
                                        {
                                            divValueType = templateValue_.Value;
                                        }
                                    }
                                }
                            }
                            if (part_T.AutomaticTyped != null && part_T.AutomaticTyped.Length > 0)
                            {
                                foreach (var automatic in part_T.AutomaticTyped)
                                {
                                    if (automatic is AutomaticTyped_T automaticValue_)
                                    {
                                        if (automaticValue_.Name == "SrcType")
                                        {
                                            autoType = true;
                                        }
                                    }
                                }
                            }
                            if (autoType)
                            {
                                //先放一个基类吧，先不考虑
                                partDict.Add(uid_str, new Div<PlcMemberBase>());
                            }
                            else if (divValueType != string.Empty)
                            {
                                if (Enum.TryParse<DataType>(divValueType, out DataType dataType))
                                {
                                    switch (dataType)
                                    {
                                        case DataType.USInt:
                                            partDict.Add(uid_str, new Div<PlcUSInt>());
                                            break;
                                        case DataType.SInt:
                                            partDict.Add(uid_str, new Div<PlcSInt>());
                                            break;
                                        case DataType.UInt:
                                            partDict.Add(uid_str, new Div<PlcUInt>());
                                            break;
                                        case DataType.Int:
                                            partDict.Add(uid_str, new Div<PlcInt>());
                                            break;
                                        case DataType.UDInt:
                                            partDict.Add(uid_str, new Div<PlcUDInt>());
                                            break;
                                        case DataType.DInt:
                                            partDict.Add(uid_str, new Div<PlcDInt>());
                                            break;
                                        case DataType.Real:
                                            partDict.Add(uid_str, new Div<PlcReal>());
                                            break;
                                        case DataType.LReal:
                                            partDict.Add(uid_str, new Div<PlcLReal>());
                                            break;
                                        default:
                                            Debug.WriteLine($"不支持的比较类型: {divValueType}");
                                            Log.LogMessage($"指令comparetwo{part_T.Name}不支持的比较类型: {divValueType}，请检查数据类型定义。");
                                            break;
                                    }
                                }
                                else
                                {
                                    Debug.WriteLine($"不支持的比较的数据类型类型: {divValueType}");
                                    Log.LogMessage($"指令comparetwo{part_T.Name}不支持的比较类型: {divValueType}，请检查数据类型定义。");
                                }
                            }
                        }
                        break;
                    case "Mod":
                        {
                            //计算的变量类型
                            string modValueType = string.Empty;
                            //自动类型判断
                            bool autoType = false;
                            if (part_T.TemplateValue != null && part_T.TemplateValue.Length > 0)
                            {
                                foreach (var templateItem in part_T.TemplateValue)
                                {
                                    if (templateItem is TemplateValue_T templateValue_)
                                    {
                                        if (templateValue_.Type == TemplateType_TE.Type
                                            && templateValue_.Name == "SrcType")
                                        {
                                            modValueType = templateValue_.Value;
                                        }
                                    }
                                }
                            }
                            if (part_T.AutomaticTyped != null && part_T.AutomaticTyped.Length > 0)
                            {
                                foreach (var automatic in part_T.AutomaticTyped)
                                {
                                    if (automatic is AutomaticTyped_T automaticValue_)
                                    {
                                        if (automaticValue_.Name == "SrcType")
                                        {
                                            autoType = true;
                                        }
                                    }
                                }
                            }
                            if ( autoType)
                            {
                                //先放一个基类吧，先不考虑
                                partDict.Add(uid_str, new Mod<PlcMemberBase>());
                            }
                            else if (modValueType != string.Empty)
                            {
                                if (Enum.TryParse<DataType>(modValueType, out DataType dataType))
                                {
                                    switch (dataType)
                                    {
                                        case DataType.USInt:
                                            partDict.Add(uid_str, new Mod<PlcUSInt>());
                                            break;
                                        case DataType.SInt:
                                            partDict.Add(uid_str, new Mod<PlcSInt>());
                                            break;
                                        case DataType.UInt:
                                            partDict.Add(uid_str, new Mod<PlcUInt>());
                                            break;
                                        case DataType.Int:
                                            partDict.Add(uid_str, new Mod<PlcInt>());
                                            break;
                                        case DataType.UDInt:
                                            partDict.Add(uid_str, new Mod<PlcUDInt>());
                                            break;
                                        case DataType.DInt:
                                            partDict.Add(uid_str, new Mod<PlcDInt>());
                                            break;
                                        case DataType.Real:
                                            partDict.Add(uid_str, new Mod<PlcReal>());
                                            break;
                                        case DataType.LReal:
                                            partDict.Add(uid_str, new Mod<PlcLReal>());
                                            break;
                                        default:
                                            Debug.WriteLine($"不支持的比较类型: {modValueType}");
                                            Log.LogMessage($"指令comparetwo{part_T.Name}不支持的比较类型: {modValueType}，请检查数据类型定义。");
                                            break;
                                    }
                                }
                                else
                                {
                                    Debug.WriteLine($"不支持的比较的数据类型类型: {modValueType}");
                                    Log.LogMessage($"指令comparetwo{part_T.Name}不支持的比较类型: {modValueType}，请检查数据类型定义。");
                                }
                            }
                        }
                        break;
                    case "Inc":
                    case "Dec":
                        {
                            //计算的变量类型
                            string incDecValueType = string.Empty;
                            //递增还是递减
                            bool inc = false;
                            if (part_T.Name == "Inc")
                            {
                                inc = true;
                            }
                            else if (part_T.Name == "Dec")
                            {
                                inc = false;
                            }
                            else
                            {
                                Log.LogMessage($"在 INCDEC中出现操作符:{part_T.Name}，请检查数据类型定义。");
                            }
                            if (part_T.TemplateValue != null && part_T.TemplateValue.Length > 0)
                            {
                                foreach (var templateItem in part_T.TemplateValue)
                                {
                                    if (templateItem is TemplateValue_T templateValue_)
                                    {
                                        if (templateValue_.Type == TemplateType_TE.Type
                                            && templateValue_.Name == "DestType")
                                        {
                                            incDecValueType = templateValue_.Value;
                                        }
                                    }
                                }
                            }
                            if (incDecValueType != string.Empty)
                            {
                                if (Enum.TryParse<DataType>(incDecValueType, out DataType dataType))
                                {
                                    switch (dataType)
                                    {
                                        case DataType.USInt:
                                            partDict.Add(uid_str, new IncDec<PlcUSInt>(inc));
                                            break;
                                        case DataType.SInt:
                                            partDict.Add(uid_str, new IncDec<PlcSInt>(inc));
                                            break;
                                        case DataType.UInt:
                                            partDict.Add(uid_str, new IncDec<PlcUInt>(inc));
                                            break;
                                        case DataType.Int:
                                            partDict.Add(uid_str, new IncDec<PlcInt>(inc));
                                            break;
                                        case DataType.UDInt:
                                            partDict.Add(uid_str, new IncDec<PlcUDInt>(inc));
                                            break;
                                        case DataType.DInt:
                                            partDict.Add(uid_str, new IncDec<PlcDInt>(inc));
                                            break;
                                        case DataType.Real:
                                            partDict.Add(uid_str, new IncDec<PlcReal>(inc));
                                            break;
                                        case DataType.LReal:
                                            partDict.Add(uid_str, new IncDec<PlcLReal>(inc));
                                            break;
                                        default:
                                            Debug.WriteLine($"不支持的比较类型: {incDecValueType}");
                                            Log.LogMessage($"指令comparetwo{part_T.Name}不支持的比较类型: {incDecValueType}，请检查数据类型定义。");
                                            break;
                                    }
                                }
                                else
                                {
                                    Debug.WriteLine($"不支持的比较的数据类型类型: {incDecValueType}");
                                    Log.LogMessage($"指令comparetwo{part_T.Name}不支持的比较类型: {incDecValueType}，请检查数据类型定义。");
                                }
                            }
                        }
                        break;

                    //移动
                    case "Move":
                        {
                            string outCount = string.Empty;
                            //用于指定比较类型
                            if (part_T.TemplateValue != null && part_T.TemplateValue.Length > 0)
                            {
                                foreach (var templateItem in part_T.TemplateValue)
                                {
                                    if (templateItem is TemplateValue_T templateValue_)
                                    {
                                        if (templateValue_.Type == TemplateType_TE.Cardinality
                                            && templateValue_.Name == "Card")
                                        {
                                            outCount = templateValue_.Value;
                                        }
                                    }
                                }
                            }
                            if (outCount != string.Empty)
                            {
                                partDict.Add(uid_str, new Move(int.Parse(outCount)));
                            }
                        }
                        break;
                    //转换操作
                    case "Convert":
                        {
                            partDict.Add(uid_str, new ConvertC() { Name = $"Convert_{uid}" });
                        }
                        break;
                    case "Round":
                        break;
                    case "Ceil":
                        break;
                    case "Floor":
                        break;

                    //字逻辑运算
                    case "And":
                    case "Or":
                    case "Xor":
                        {
                            string logicDataType = string.Empty;
                            string inCount = string.Empty;
                            //用于指定比较类型
                            if (part_T.TemplateValue != null && part_T.TemplateValue.Length > 0)
                            {
                                foreach (var templateItem in part_T.TemplateValue)
                                {
                                    if (templateItem is TemplateValue_T templateValue_)
                                    {
                                        if (templateValue_.Type == TemplateType_TE.Type
                                            && templateValue_.Name == "SrcType")
                                        {
                                            logicDataType = templateValue_.Value;
                                        }
                                        if (templateValue_.Type == TemplateType_TE.Cardinality
                                            && templateValue_.Name == "Card")
                                        {
                                            inCount = templateValue_.Value;
                                        }
                                    }
                                }
                            }
                            if (logicDataType != string.Empty && inCount != string.Empty)
                            {
                                if (Enum.TryParse<DataType>(logicDataType, out DataType dataType) &&
                                    Enum.TryParse<WordLogicOperation>(part_T.Name, out WordLogicOperation logicOperationType))
                                {
                                    switch (dataType)
                                    {
                                        case DataType.Byte:
                                            partDict.Add(uid_str, new AndOrXor<PlcByte>(int.Parse(inCount), logicOperationType) { Name = $"{part_T.Name}_{uid}" });
                                            break;
                                        case DataType.Word:
                                            partDict.Add(uid_str, new AndOrXor<PlcWord>(int.Parse(inCount), logicOperationType) { Name = $"{part_T.Name}_{uid}" });
                                            break;
                                        case DataType.DWord:
                                            partDict.Add(uid_str, new AndOrXor<PlcDWord>(int.Parse(inCount), logicOperationType) { Name = $"{part_T.Name}_{uid}" });
                                            break;
                                        default:
                                            Log.LogMessage($"指令range:{part_T.Name}不支持的比较类型: {logicDataType}，请检查数据类型定义。");
                                            break;
                                    }
                                }
                                else
                                {
                                    Debug.WriteLine($"不支持的比较的数据类型类型: {logicDataType}");
                                }
                            }
                        }
                        break;
                    //移位和循环
                    case "Shr":
                        break;
                    case "Shl":
                        break;
                    case "Rr":
                        break;
                    case "Rl":
                        break;
                    //扩展指令
                    case "WR_SYS_T":
                        break;
                    case "RD_SYS_T":
                        break;
                    case "S_Move":
                        {
                            partDict.Add(uid_str, new S_Move() { Name = $"S_Move_{uid}" });
                        }
                        break;


                }
            }
        }
        private static void ParseCall(Call_T call_T, Dictionary<string, IGraphNode> partDict)
        {
            ///call的调用需要绑定实例和参数
            ///FB需要绑定实例，如有参数则绑定参数
            ///FC只需要绑定参数
            if (call_T != null)
            {
                var call = new CustomCall();
                int uid = call_T.UId;
                string call_name = call_T.CallInfo.Name;
                string call_type = Enum.GetName(typeof(BlockType_TE), call_T.CallInfo.BlockType) ?? string.Empty;
                call.CallType = call_type;
                //只对FB做绑定实例解析
                if (call_T.CallInfo.BlockType == BlockType_TE.FB &&
                    call_T.CallInfo.Items != null &&
                    call_T.CallInfo.Items.Length > 0)
                {
                    foreach (var callInfoItem in call_T.CallInfo.Items)
                    {
                        //存在绑定变量，只解析实例
                        if (callInfoItem is Instance_T)
                        {
                            var _instance = (Instance_T)callInfoItem;
                            var instanceScope = Enum.GetName(typeof(Scope_TE), _instance.Scope) ?? string.Empty;
                            var instanceUId = _instance.UId;
                            if (_instance.Items != null && _instance.Items.Length > 0)
                            {
                                foreach (var instanceItem in _instance.Items)
                                {
                                    if (instanceItem is Component_T)
                                    {
                                        var _component = (Component_T)instanceItem;
                                        var instance = ParseComponent(_component);
                                        Debug.WriteLine("实例名称：{0}，实例类型：{1}", instance, instanceScope);
                                        call.Instance = $"实例名称：{instance}，实例类型：{instanceScope}";
                                    }
                                }
                            }
                        }
                        //变量也得绑定
                        else if (callInfoItem is Parameter_T parameter)
                        {
                            call.variableTableInterface.AddVariable(parameter.Name, (StorageType)Enum.Parse(typeof(StorageType), parameter.Section.ToString()));
                        }

                    }
                }
                partDict.Add(uid.ToString(), call);
                Debug.WriteLine($"Call UID: {uid}，call_name:{call_name},call_type:{call_type}");

            }
        }
        private static string ParseAccess(Access_T access_T)
        {
            if (access_T != null)
            {
                var uid = access_T.UId;
                var scope = access_T.Scope;
                if (access_T.Item != null)
                {
                    if (access_T.Item is Constant_T)
                    {
                        //如果uid>1则表示用于进行图元连接，否则表示数组下标
                        var item = (Constant_T)access_T.Item;
                        if (uid > 0)
                        {
                            //格式：uid+scope+value
                            return $"{uid}+{scope}+{item.ConstantValue.Value}";
                        }
                        else
                        {
                            return item.ConstantValue.Value;
                        }

                    }
                    else if (access_T.Item is Symbol_T symbolItem)
                    {
                        if (symbolItem.Items != null && symbolItem.Items.Length > 0)
                        {
                            string varname = string.Empty;
                            foreach (var symbolItemObj in symbolItem.Items)
                            {
                                if (symbolItemObj is Component_T)
                                {
                                    var _component = (Component_T)symbolItemObj;
                                    var componentName = ParseComponent(_component);
                                    varname += componentName;
                                    varname += ".";
                                }
                            }
                            varname = varname.TrimEnd('.');
                            //如果uid>1则表示用于进行图元连接，否则表示数组下标
                            if (uid > 0)
                            {
                                return $"{uid}+{scope}+{varname}";
                            }
                            else
                            {
                                return $"{uid}-{scope}-{varname}";
                            }

                        }
                    }

                }
            }
            return string.Empty;
        }
        private static string ParseComponent(Component_T component_T)
        {
            if (component_T != null)
            {
                AccessModifier_TE c_accessModifier = component_T.AccessModifier;
                var c_name = component_T.Name;
                //处理数组
                if (component_T.AccessModifier == AccessModifier_TE.Array)
                {
                    if (component_T.Items != null && component_T.Items.Length > 0)
                    {
                        foreach (var compItem in component_T.Items)
                        {
                            if (compItem is Access_T)
                            {
                                var _access = (Access_T)compItem;
                                string index = ParseAccess(_access);
                                if (index.Contains('+'))
                                {
                                    Log.LogMessage($"严重错误!!!!!!!!!!!!{index}");
                                    //Environment.Exit(0); // 使用退出代码 0 退出程序
                                }
                                Debug.WriteLine($"[{index}]");
                                return $"{c_name}[{index}]";
                            }
                        }
                    }
                }
                //处理位
                //<Symbol>
                //  < Component Name = "源INT" SliceAccessModifier = "x11" />
                //</ Symbol >
                // .%x0
                else if (component_T.SliceAccessModifier != "undef")
                {
                    return $"{c_name}.%{component_T.SliceAccessModifier}";
                }
                else if (component_T.AccessModifier == AccessModifier_TE.None)
                {
                    return $"{c_name}";
                }



            }
            return string.Empty;
        }

        private static void ParseWire(Wire_T wire_T,
            Dictionary<string, DataPointer> accessDic,
            Dictionary<string, IGraphNode> partDict,
            Powerrail netNode)
        {
            if (wire_T != null)
            {
                var uid = wire_T.UId;
                List<(IGraphNode, string)> tupleList = new List<(IGraphNode, string)>();
                int connectedCount = wire_T.Items.Length;
                if (connectedCount > 1)
                {
                    //数据绑定
                    if (connectedCount == 2 &&
                        (wire_T.Items[0] is IdentCon_T ||
                         wire_T.Items[1] is IdentCon_T ||
                         wire_T.Items[0] is OpenCon_T ||
                         wire_T.Items[1] is OpenCon_T))//数据绑定只能是两个,并且存在一定限制条件
                    {

                        //todo 数据绑定，
                        string identCon_id = string.Empty;
                        string nameCon_id = string.Empty;
                        string nameCon_name = string.Empty;
                        string openCon_id = string.Empty;
                        foreach (var conItem in wire_T.Items)
                        {
                            if (conItem is NameCon_T nameCon)
                            {
                                nameCon_id = nameCon.UId.ToString();
                                nameCon_name = nameCon.Name;
                            }
                            else if (conItem is IdentCon_T identCon)
                            {
                                identCon_id = identCon.UId.ToString();
                            }
                            else if (conItem is OpenCon_T openCon)
                            {
                                nameCon_id = openCon.UId.ToString();
                            }
                        }
                        //namecom不为空
                        if (nameCon_id != string.Empty)
                        {
                            if (identCon_id != string.Empty)
                            {
                                if (partDict.TryGetValue(nameCon_id, out IGraphNode? node) &&
                                    accessDic.TryGetValue(identCon_id, out DataPointer? data))
                                {
                                    if (node is ElementNodeBase element)
                                    {
                                        element.dataPointerAssociation.AddDataPointer(nameCon_name, data);
                                    }

                                }
                                else
                                {
                                    Log.LogMessage($"严重错误,没有找到节点{uid}的NameCon|identCon,");
                                    //Environment.Exit(0); // 使用退出代码 0 退出程序
                                }
                            }
                            else if (openCon_id != string.Empty)
                            {
                                if (partDict.TryGetValue(nameCon_id, out IGraphNode? node))
                                {
                                    var openData = new DataPointer();
                                    openData.Symbols.Add($"OpenCon+{openCon_id}");
                                    if (node is ElementNodeBase element)
                                    {
                                        element.dataPointerAssociation.AddDataPointer(nameCon_name, openData);
                                    }
                                }
                                else
                                {
                                    Log.LogMessage($"严重错误,没有找到节点{uid}的NameCon");
                                    //Environment.Exit(0); // 使用退出代码 0 退出程序
                                }
                            }
                        }


                    }
                    else
                    {
                        foreach (var conItem in wire_T.Items)
                        {
                            if (conItem is Powerrail_T)
                            {
                                var powerrail = new Powerrail();
                                tupleList.Add((powerrail, "Powerrail"));
                            }
                            else if (conItem is NameCon_T nameCon)
                            {
                                var name = nameCon.Name;
                                var uid_str = nameCon.UId.ToString();
                                if (partDict.ContainsKey(uid_str))
                                {
                                    var node = partDict[uid_str];
                                    tupleList.Add((node, name));
                                }
                                else
                                {
                                    Log.LogMessage($"严重错误,没有找到节点{uid_str}");
                                    //Environment.Exit(0); // 使用退出代码 0 退出程序
                                }
                            }
                        }
                        if (tupleList.Count > 1)
                        {
                            WireConnector.Connect(netNode, tupleList);
                        }
                    }

                }
            }
        }
        #endregion
        public class Log
        {
            public static void LogMessage(string message,
                          [CallerFilePath] string file = "",
                          [CallerLineNumber] int line = 0)
            {

                Debug.WriteLine($"{message} (位置: {file} 第 {line} 行)");

            }
        }
    }

}
